//
//  AXFHomeController.m
//  Home
//
//  Created by HH on 16/11/22.
//  Copyright © 2016年 adad. All rights reserved.
//

#import "AXFHomeController.h"
#import "AXFHomeLayout.h"
#import "AXFHomeHeaderView.h"
#import "AXFBtnCell.h"
#import "AXFDiscountCell.h"
#import "AXFPictureCell.h"
#import "AXFClassifyCell.h"
#import "AXFClassifyGoodsCell.h"
#import "AXFNavView.h"
#import "AXFCommonModel.h"
#import "AXFDetailModel.h"
#import "AXFDetailsModel.h"
#import <PYSearch.h>
#import "AXFHUDView.h"
#import <MJRefresh.h>
#import "AXFFlashSupermarketController.h"
#import "AXFNavigationController.h"
#import "AXFScancodeController.h"
#import "AXFDetailViewController.h"

static NSString *cellID = @"cellID";
static NSString *btnCellID = @"btnCellID";
static NSString *discountCellID = @"discountCellID";
static NSString *pictureCellID = @"pictureCellID";
static NSString *classifyCellID = @"classifyCellID";
static NSString *classifyGoodsCellID = @"classifyGoodsCellID";
static NSString *headerViewID = @"headerViewID";
@interface AXFHomeController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, AXFNavViewDelegate, AXFHomeHeaderViewDelegate, AXFClassiyGoodsCellDelegate, CAAnimationDelegate>

@property (nonatomic,weak)UICollectionView *collectionView;

@property (nonatomic,weak)AXFNavView *navView;

@property (nonatomic,strong)NSArray<NSString *> *hotSeaches;

@property (nonatomic,strong)NSArray<NSDictionary *> *homeData;

@property (nonatomic,strong)NSArray<NSDictionary *> *classifyData;

@property (nonatomic,weak)UIView *hudView;

@property (nonatomic,weak)UIView *backgroundHUDView;

@property (nonatomic,weak)MJRefreshGifHeader *refreshHeader;

@end

@implementation AXFHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadData];
    [self pulldownRefresh];
    // Do any additional setup after loading the view.
}

// cell 的代理方法
- (void)addGoodsWithCell:(AXFClassifyGoodsCell *)cell model:(AXFDetailsModel *)model goodsPicLoc:(CGPoint)picLoc {
	NSDictionary *userInfo = @{@"model":model};
	[[NSNotificationCenter defaultCenter] postNotificationName:@"homeToMarket" object:self userInfo:userInfo];
	
	[self creatAnimateStartPoint:picLoc WithModel:model];
	
	
}

- (void)setupUI
{
    self.view.backgroundColor = [UIColor yellowColor];
    
//    UIView *backgroundView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
//    
//    self.backgroundHUDView = backgroundView;
    
    UIView *hudView = [AXFHUDView creatHudViewWithHUDLoadingTitle:@"正在加载中..." titleFont:12.0 HUDMode:MBProgressHUDModeIndeterminate];
    
    hudView.center = self.view.center;
    
    self.hudView = hudView;
    
//    [self.backgroundHUDView addSubview:hudView];
    
    
    AXFHomeLayout *layout = [[AXFHomeLayout alloc] init];
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    
    self.collectionView = collectionView;
    
    collectionView.dataSource = self;
    
    collectionView.delegate = self;
    
    //    [collectionView setContentOffset:CGPointMake(0, 20)];
    
    collectionView.backgroundColor = [UIColor cz_colorWithHex:0xebebeb];
    
    [self.view addSubview:collectionView];
    
//    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.top.right.equalTo(self.view);
//        make.height.mas_equalTo(160);
//    }];
    
    AXFNavView *navView = [[AXFNavView alloc] init];
    
    self.navView = navView;
    
    navView.delegate = self;
    
    [self.view addSubview:navView];
    
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.offset(-20);
    }];
    
    [navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(kNAVBARH + 20);
    }];
    
//    [self.view addSubview:self.backgroundHUDView];
    [self.view insertSubview:hudView belowSubview:navView];
    
    NSArray<NSDictionary *> *cellArr = @[
   @{@"cellID":btnCellID,@"class":[AXFBtnCell class]},
   @{@"cellID":discountCellID,@"class":[AXFDiscountCell class]},
   @{@"cellID":pictureCellID,@"class":[AXFPictureCell class]},
   @{@"cellID":classifyCellID,@"class":[AXFClassifyCell class]},
   @{@"cellID":classifyGoodsCellID,@"class":[AXFClassifyGoodsCell class]},
   @{@"cellID":cellID,@"class":[UICollectionViewCell class]}
   ];
    
    [cellArr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [collectionView registerClass:obj[@"class"] forCellWithReuseIdentifier:obj[@"cellID"]];
    }];
    
    [collectionView registerClass:[AXFHomeHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewID];
}


#pragma mark - 刷新
- (void)pulldownRefresh
{
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    
    self.refreshHeader = header;
    
    NSArray *imageArr = @[[UIImage imageNamed:@"v2_pullRefresh1"],
                          [UIImage imageNamed:@"v2_pullRefresh2"]];
    
    [header setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
    [header setTitle:@"松开刷新" forState:MJRefreshStatePulling];
    
    [header setImages:imageArr forState:MJRefreshStatePulling];
    
    self.collectionView.mj_header = header;
}

- (void)loadNewData
{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
    });
    
}

#pragma mark -加载数据
- (void)loadData
{
    __block NSMutableArray<NSDictionary *> *tempArr = [NSMutableArray array];
    
    [[AXFNetworkingTools sharedManager] getHomeDataComplete:^(id responseOBJ, NSError *error) {
        
        [self.refreshHeader endRefreshing];
        [self.hudView removeFromSuperview];
        
        tempArr = [responseOBJ[@"data"][@"act_info"] mutableCopy];
        
        [tempArr removeObjectAtIndex:2];
        
        self.homeData = tempArr.copy;
        
        [self.homeData enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            switch (idx) {
                case 0:
//                    self.cycleData = obj[ACT_ROWS];
                    break;
                case 1:
//                    self.displayBtnData = obj[ACT_ROWS];
                case 2:
//                    self.discountData = obj[ACT_ROWS];
                case 3:
//                    self.convenienceData = obj[ACT_ROWS];
                case 4:
                    self.classifyData = obj[ACT_ROWS];
                default:
                    break;
            }
            
        }];
        
        
        
        [self.collectionView reloadData];
        
        
        
    }];
}

#pragma mark - 轮播图跳转到详情页
- (void)jumpToDetailsController:(AXFCommonModel *)commonModel
{
    AXFDetailViewController *detailViewController = [[AXFDetailViewController alloc] init];
    
    detailViewController.commonModel = commonModel;
    
    [self.navigationController pushViewController:detailViewController animated:YES];
}


#pragma mark - 跳转到扫一扫界面
- (void)pushToScancodeController
{
    AXFScancodeController *scancodeController = [[AXFScancodeController alloc] init];
    
    [self.navigationController pushViewController:scancodeController animated:YES];
}

#pragma mark - 搜索
- (void)presentSearchViewController
{
    //热门搜索
    self.hotSeaches = @[@"大闸蟹",@"水",@"中秋月饼",@"酸奶",@"啤酒",@"西瓜",@"大荔冬枣",@"贝尔蛋糕",@"月盛斋",@"方便面"];
    
    PYSearchViewController *searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:self.hotSeaches searchBarPlaceholder:@"请输入商品名称" didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        
    }];
    
    searchViewController.hotSearchStyle = PYHotSearchStyleColorfulTag;
    searchViewController.searchHistoryStyle = PYSearchHistoryStyleARCBorderTag;
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchViewController];
    
    [self presentViewController:nav animated:YES completion:nil];
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        AXFBtnCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:btnCellID forIndexPath:indexPath];
        
        NSDictionary *dict = self.homeData[indexPath.section + 1][ACT_ROWS][indexPath.item][ACTIVITY];
        
        AXFCommonModel *model = [AXFCommonModel yy_modelWithDictionary:dict];
        
        cell.model = model;
         
        return cell;
    }
    
    if (indexPath.section == 1) {
        AXFDiscountCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:discountCellID forIndexPath:indexPath];
        cell.disCountArr = self.homeData[indexPath.section + 1][ACT_ROWS];
        
        return cell;
    }
    
    if (indexPath.section == 2) {
        if (indexPath.item >= 0 && indexPath.item <= 2) {
            AXFPictureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:pictureCellID forIndexPath:indexPath];
            
            if (indexPath.item == 0) {
                NSDictionary *dict= self.homeData[3][ACT_ROWS][0][ACT_ROWS][indexPath.item][@"chead_detail"];
                
                AXFCommonModel *model = [AXFCommonModel yy_modelWithJSON:dict];
                
                cell.model = model;
            }else{
                
                NSDictionary *dict = self.homeData[3][ACT_ROWS][1][ACT_ROWS][indexPath.item - 1][@"cactivity_detail"];
                
                AXFCommonModel *model = [AXFCommonModel yy_modelWithDictionary:dict];
                
                cell.model = model;
            }
            
            return cell;
        }else if (indexPath.item >= 3 && indexPath.item <= 6){
            
            AXFBtnCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:btnCellID forIndexPath:indexPath];
            
            NSDictionary *dict = self.homeData[3][ACT_ROWS][2][ACT_ROWS][indexPath.item - 3][@"cicons_detail"];
            
//            NSLog(@"++++%@",self.homeData[3][ACT_ROWS][indexPath.item - 3]);
            AXFCommonModel *model = [AXFCommonModel yy_modelWithDictionary:dict];
            cell.model = model;
            
            return cell;
        }
        
        AXFPictureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:pictureCellID forIndexPath:indexPath];
        NSDictionary *dict = self.homeData[3][ACT_ROWS][3][ACT_ROWS][indexPath.item - 7][ACTIVITY];
        
        AXFCommonModel *model = [AXFCommonModel yy_modelWithDictionary:dict];
        cell.model = model;
        
        return cell;
    }
    
    if (indexPath.item == 0) {
        AXFClassifyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:classifyCellID forIndexPath:indexPath];
        
        NSDictionary *dict = self.homeData[4][ACT_ROWS][indexPath.section - 3][ACTIVITY];
        
        AXFCommonModel *model = [AXFCommonModel yy_modelWithDictionary:dict];
        
        cell.model = model;
        
        NSDictionary *detailDict = self.homeData[4][ACT_ROWS][indexPath.section - 3][@"category_detail"];
        
        AXFDetailModel *detailModel = [AXFDetailModel yy_modelWithDictionary:detailDict];
        cell.detailModel = detailModel;
        
        return cell;
    }
    
    AXFClassifyGoodsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:classifyGoodsCellID forIndexPath:indexPath];
    
    NSDictionary *dict = self.homeData[4][ACT_ROWS][indexPath.section - 3][@"category_detail"];
    
    AXFDetailModel *detailModel = [AXFDetailModel yy_modelWithDictionary:dict];
    
    NSArray *goodsArr = detailModel.goods;
    
    cell.model = goodsArr[indexPath.item - 1];
	cell.delegate = self;
    
    return cell;

}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        AXFHomeHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewID forIndexPath:indexPath];
        
        headerView.cycleArr = self.homeData[indexPath.section][ACT_ROWS];
        headerView.delegate = self;
        
        return headerView;
    }
    
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeMake(kSCREENWIDTH, 160);
    }
    
    return CGSizeZero;
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.classifyData.count + self.homeData.count - 2 ;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return 4;
    }
    
    if (section == 1) {
        return 1;
    }
    
    if (section == 2) {
        return 9;
    }
    
    return 4;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        
        CGFloat width = kSCREENWIDTH / 4;
        
        return CGSizeMake(width, 80);
    }
    
    if (indexPath.section == 1) {
        
        
        return CGSizeMake(kSCREENWIDTH, 140);
    }
    
    if (indexPath.section == 2) {
    
        if (indexPath.item == 0) {
            return CGSizeMake(kSCREENWIDTH, 60);
        }else if (indexPath.item == 1 || indexPath.item == 2){
            
            CGFloat width = kSCREENWIDTH / 2;
            return CGSizeMake(width, 70);
        }else if (indexPath.item >= 3 && indexPath.item <= 6){
            CGFloat width = kSCREENWIDTH / 4;
            
            return CGSizeMake(width, 85);
        }
        CGFloat width = (kSCREENWIDTH - 1) / 2;
        
        return CGSizeMake(width, 75);
    }
    
    if (indexPath.item == 0) {
        return CGSizeMake(kSCREENWIDTH, 140);
    }else{
        CGFloat width = (kSCREENWIDTH - 2) / 3;
        return CGSizeMake(width, 196);
    }
    
    return CGSizeZero;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    if (section > 2) {
        return 1;
    }
    
    return 0;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    AXFNavigationController *navController = self.tabBarController.childViewControllers[1];
    
    AXFFlashSupermarketController *flashSuperMarketController = (AXFFlashSupermarketController *)navController.topViewController;
    
    if (indexPath.section == 2) {
        if (indexPath.item <= 6 && indexPath.item > 0) {
            
            flashSuperMarketController.homeIndexItem = indexPath.item - 1;
            
            self.tabBarController.selectedIndex = 1;
        }
    }
}

#pragma mark - 监听collectionView的滚动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //    NSLog(@"%@",NSStringFromCGPoint(scrollView.contentOffset));18501617582
    
    CGPoint offset = scrollView.contentOffset;
    
    CGFloat alpha = (offset.y + 20) / 96;
    
    //    NSLog(@"%f",alpha);
    
    //    [self.navigationController.navigationBar setNavBarColor:nil andAlpha:alpha];
    
    [self.navView setContainerViewAlpha:alpha];
    
    //    self.navigationController.navigationBar.alpha = alpha;
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
    
//    self.navView.locationName = [[NSUserDefaults standardUserDefaults] objectForKey:@"locationName"];
}


// 添加商品动画
// 创建动画
- (void)creatAnimateStartPoint:(CGPoint)startPoint WithModel:(AXFDetailsModel *)model
{
	UIImageView *currentImage = [[UIImageView alloc]init];
	NSURL *urlStr = [NSURL URLWithString:model.img];
	currentImage.backgroundColor = [UIColor redColor];
	currentImage.bounds = CGRectMake(0, 0, 80, 80);
	//    [currentImage sd_setImageWithURL:urlStr];
	[currentImage sd_setImageWithURL:urlStr completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
		currentImage.center = startPoint;
		//    NSLog(@"+++++");
		//获取 当时获取坐标位置的window
		UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
		//添加图片
		[keyWindow addSubview:currentImage];
		//创建一个关键帧动画    才能一次执行多个动画  否则普通动画只能执行一个      position：位置  移动位置
		CAKeyframeAnimation *keyAni = [CAKeyframeAnimation animationWithKeyPath:@"position"];
		//   贝塞尔曲线
		UIBezierPath *path = [UIBezierPath bezierPath];
		// 起点
		[path moveToPoint:startPoint];
		
		// 跳跃位置
		//        CGPoint middlePoint = CGPointMake(startPoint.x, startPoint.y - 44);
		
		// 终点的位置
		CGPoint endPoint = CGPointMake(200, 667 - 44);
		
		//  设置路径
		[path addLineToPoint:endPoint];
		//        [path addCurveToPoint:endPoint controlPoint1:startPoint controlPoint2:middlePoint];
		keyAni.path = path.CGPath;
		//时间
		keyAni.duration = .5;
		[UIView animateWithDuration:.5 animations:^{
			
			currentImage.transform = CGAffineTransformMakeScale(0.2, 0.2);
		}];
		
		//  遵守代理    这个是animation独有的
		keyAni.delegate = self;
		
		//    5.在动画结束之后删除      在动画添加之前 保存到字典中
		[keyAni setValue:currentImage forKey:@"endImage"];
		
		[currentImage.layer addAnimation:keyAni forKey:@"keyAni"];
	}];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
	UIImageView *endView = [anim valueForKey:@"endImage"];
	[endView removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
